DOM 節點 相關屬性


Posted by mijouhsieh on 2022-05-06

節點有多種屬性可以選取其上下關係(父層、子層),或左右關係(前後元素)
使用 Element-only語法,getter 屬性 選出周邊的node
parentElement
previousElement
nextElement
children 會回傳array-like 的節點清單 // HTMLCollection (3) [li, li, li]
firstElementChild
lastElementChild
都回傳特定的一個node,除了children。


選出 node 的內容

  1. node.innerHTML
  2. node.textContent
  3. node.innerText

方法
node.before(nodes) node前(同一層)增加
node.prepend(nodes) 子層開頭增加
node.append(nodes) 子層結尾增加
node.after(nodes) node後(同一層)增加

const 變數 = document.createElement('h1')
node.appendChild(變數) node新增子層
node.insertBefore(要加的元素, 加入位置)
node.replaceChild(要加的元素, 加入位置)
用法:

<ul>.prepend(<li>) 
<ul>.prepend('字串')
for (let i = 0; i < 4; i++) {
  console.log(document.querySelectorAll('tbody tr')[i].children[0].textContent)
}
const rows = document.querySelectorAll('.table tbody tr')
for (let i = 0; i < rows.length; i ++) {
  console.log(rows[i].firstElementChild.innerHTML)
}

children[0] 也可以寫成 firstElementChild


#DOM #firstElementChild #querySelector #getter #selectors #method







Related Posts

BTC original source code(C++) initial 架構分析  (1)

BTC original source code(C++) initial 架構分析 (1)

Selenium with JS and infinite scroll

Selenium with JS and infinite scroll

D52_W7 DOM 少年事件簿之真珠美人魚

D52_W7 DOM 少年事件簿之真珠美人魚


Comments